import { Context, Next } from 'koa';
import path from 'path';
import fs from 'fs';

const staticDir = path.join(__dirname, '../../../../../mobile-web/dist');

/**
 * SPA 路由处理中间件
 * 对于不存在的路由返回 index.html
 */
export default function spaMiddleware() {
    return async (ctx: Context, next: Next) => {
        await next();
        if (ctx.status === 404 && !ctx.path.startsWith('/api')) {
            ctx.type = 'text/html';
            ctx.body = fs.readFileSync(path.join(staticDir, 'index.html'), 'utf8');
        }
    };
} 